<?php

namespace app\api\controller;

use app\admin\model\Order as OrderMdl;
use app\admin\model\Orderitem;
use app\admin\model\Product;

class Order extends BaseController
{

    /**
     * 获取样品申领列表
     */
    public function getReceiveorderList()
    {
        $param = self::getHttpParam();

        $start = 0;
        $length = 20;

        if (empty($param->townId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'townId 不能为空');
        }
        if (empty($param->userId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'userId 不能为空');
        }
        if (!empty($param->start)) {
            $start = $param->start;
        }
        if (!empty($param->length)) {
            $length = $param->length;
        }
        $where = [
            'townId' => $param->townId,
            'userId' => $param->userId
        ];

        $model = new OrderMdl();
        $fields = 'id, orderNO, status, totalCount, totalAmount, expressName, expressNo, deliverAddress, mail, userName, userPhone, content';
        // 默认 最新上架
        $order = 'createDate DESC';
        $result = $model->where($where)->field($fields)->limit($start, $length)->order($order)->select();
        $total = $model->where($where)->count();
        if (!$result) {
            return show(config('status.ERROR_STATUS'), self::NOT_DATA, '没有相关数据');
        }

        $areaDB = db('area');
        foreach ($result as &$item) {
            // 订单详情
            $orderitem = Orderitem::where('orderId', $item['id'])->field('productId, productName, productImg, productAddress, price, count, oldStatus')->select();
            $item['orderitem'] = $orderitem;
        }

        return showTotal(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $result, $total);
    }

    /**
     * 获取详情
     */
    public function getDetail()
    {
        $param = self::getHttpParam();

        if (empty($param->orderId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'orderId 不能这空');
        }
        if (empty($param->userId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'userId 不能为空');
        }

        $where = [
            'id' => $param->orderId
        ];
        $fields = 'id, orderNO, status, totalCount, totalAmount, expressName, expressNo, deliverAddress, mail, userName, userPhone, content, mcontent';

        $model = new OrderMdl();
        $item = $model->where($where)->order('createDate DESC')->field($fields)->find();

        if (empty($item)) {
            return show(config('status.ERROR_STATUS'), self::NOT_DATA, '未查到相关订单');
        }

        // 订单详情
        $orderitem = Orderitem::where('orderId', $item['id'])->field('productId, productName, productImg, productAddress, price, count, oldStatus')->select();
        $item['orderitem'] = $orderitem;

        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $item);
    }

}